package com.ithuang.websocket.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.exceptions.*;

import java.util.Calendar;
import java.util.Map;

public class jwtUtils {

    private static final String SECRET = "XIAOSHUANG"; // 确保密钥安全存储

    /**
     * 生成token
     */
    public static String getToken(Map<String, String> claims) {
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, 7); // 设置过期时间为当前时间后的7天

            JWTCreator.Builder builder = JWT.create();
            for (Map.Entry<String, String> entry : claims.entrySet()) {
                builder.withClaim(entry.getKey(), entry.getValue());
            }
            return builder.withExpiresAt(calendar.getTime())
                    .sign(Algorithm.HMAC256(SECRET));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 验证token
     */
    public static DecodedJWT verify(String token) throws JWTVerificationException {
        try {
            return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        } catch (TokenExpiredException e) {
            throw new JWTVerificationException("Token expired", e);
        } catch (SignatureVerificationException e) {
            throw new JWTVerificationException("Invalid signature", e);
        } catch (AlgorithmMismatchException e) {
            throw new JWTVerificationException("Algorithm mismatch", e);
        } catch (JWTDecodeException e) {
            throw new JWTVerificationException("Error decoding token", e);
        } catch (Exception e) {
            throw new JWTVerificationException("Error verifying token", e);
        }
    }

    /**
     * 获取token信息
     */
    public static DecodedJWT getTokenInfo(String token) throws JWTVerificationException {
        try {
            return verify(token); // 验证token的同时获取DecodedJWT对象
        } catch (JWTVerificationException e) {
            throw e; // 重新抛出自定义异常，调用者可以处理这些异常
        }
    }

    // 自定义异常类，用于token验证失败时抛出
    public static class JWTVerificationException extends Exception {
        public JWTVerificationException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}